<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="1.编写线程安全的单例模式。实现方式一：12345678910// 利用静态内部类实现单例模式（极力推荐）public class Singleton&amp;#123; //“延迟加载”，“线程安全”    private Singleton()&amp;#123; &amp;#125;    private static class T&amp;#123; //静态内部类在使用的时候才加载，且只加载一次   private">
<meta property="og:type" content="article">
<meta property="og:title" content="JAVA 设计模型相关">
<meta property="og:url" content="https://mingmingv.gitee.io/2018/11/01/JAVA-设计模型相关/index.html">
<meta property="og:site_name" content="四 季">
<meta property="og:description" content="1.编写线程安全的单例模式。实现方式一：12345678910// 利用静态内部类实现单例模式（极力推荐）public class Singleton&amp;#123; //“延迟加载”，“线程安全”    private Singleton()&amp;#123; &amp;#125;    private static class T&amp;#123; //静态内部类在使用的时候才加载，且只加载一次   private">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-11-01T12:24:13.719Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JAVA 设计模型相关">
<meta name="twitter:description" content="1.编写线程安全的单例模式。实现方式一：12345678910// 利用静态内部类实现单例模式（极力推荐）public class Singleton&amp;#123; //“延迟加载”，“线程安全”    private Singleton()&amp;#123; &amp;#125;    private static class T&amp;#123; //静态内部类在使用的时候才加载，且只加载一次   private">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://mingmingv.gitee.io/2018/11/01/JAVA-设计模型相关/">





  <title>JAVA 设计模型相关 | 四 季</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">四 季</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://mingmingv.gitee.io/2018/11/01/JAVA-设计模型相关/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="四 季">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="四 季">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">JAVA 设计模型相关</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-11-01T17:01:47+08:00">
                2018-11-01
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="1-编写线程安全的单例模式。"><a href="#1-编写线程安全的单例模式。" class="headerlink" title="1.编写线程安全的单例模式。"></a>1.编写线程安全的单例模式。</h1><h2 id="实现方式一："><a href="#实现方式一：" class="headerlink" title="实现方式一："></a>实现方式一：</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">// 利用静态内部类实现单例模式（极力推荐）</span><br><span class="line">public class Singleton&#123; //“延迟加载”，“线程安全”</span><br><span class="line">    private <span class="function"><span class="title">Singleton</span></span>()&#123; &#125;</span><br><span class="line">    private static class T&#123; //静态内部类在使用的时候才加载，且只加载一次</span><br><span class="line">   private static Singleton t=new Singleton();</span><br><span class="line">&#125;</span><br><span class="line">public static Singleton <span class="function"><span class="title">getInstance</span></span>()&#123;</span><br><span class="line"><span class="built_in">return</span> T.t;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="实现方式二："><a href="#实现方式二：" class="headerlink" title="实现方式二："></a>实现方式二：</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">// 双重校验锁 DCL(double checked locking)--使用 volatile 的场景之一</span><br><span class="line">public class Singleton &#123;</span><br><span class="line">    //注意需要用 volatile 关键字</span><br><span class="line">    private static volatile Singleton instance = null;</span><br><span class="line">    private <span class="function"><span class="title">Singleton</span></span>() &#123;&#125;</span><br><span class="line">    //双重检查加锁，只有在第一次实例化时，才启用同步机制，提高了性能。</span><br><span class="line">    public static Singleton <span class="function"><span class="title">getInstance</span></span>() &#123;</span><br><span class="line">        <span class="keyword">if</span> (instance == null) &#123;</span><br><span class="line">            synchronized (Singleton.class) &#123;</span><br><span class="line">             <span class="keyword">if</span> (instance == null) &#123;</span><br><span class="line">                 instance = new Singleton();//注意这条语句，非原子操作</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">    <span class="built_in">return</span> instance;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>现在想象一下有线程 A 和 B 在调用 getInstance()，线程 A 先进入，在执行到 instance=new Singleton():的时候被踢出了 cpu。然后线程 B 进入，B看到的是 instance 已经不是 null 了（内存已经分配），于是它开始放心地使用instance，但这个是错误的，因为 A 还没有来得及完成 instance 的初始化,而线程 B 就返回了未被初始化的 instance 实例（为了禁止指令重排序，就用 volatile关键字）。</p>
</blockquote>
<h2 id="实现方式三："><a href="#实现方式三：" class="headerlink" title="实现方式三："></a>实现方式三：</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">public class SafeLazyInitialization &#123;</span><br><span class="line">    private static Resource resource;</span><br><span class="line">        public synchronized static Resource <span class="function"><span class="title">getInstance</span></span>() &#123;</span><br><span class="line">            <span class="keyword">if</span> (resource == null)</span><br><span class="line">                resource = new Resource();</span><br><span class="line">            <span class="built_in">return</span> resource;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>单例模式应用场景：</li>
</ul>
<blockquote>
<p>数据库连接池，多线程的线程池。 <strong>Windows 的任务管理器就是很典型的单例模式。</strong></p>
</blockquote>
<p>2.享元模式<br>String 采用了享元设计模式（flyweight）。</p>
<p>3.原型模式</p>
<pre><code>原型模式主要用于对象的复制，实现一个接口（实现 Cloneable 接口），
</code></pre><p>重写一个方法（重写 Object 类中的 clone 方法），即完成了原型模式。<br>    原型模式中的拷贝分为”浅拷贝”和”深拷贝”:<br>    浅拷贝: 对值类型的成员变量进行值的复制,对引用类型的成员变量只复制<br>引用,不复制引用的对象.<br>    深拷贝: 对值类型的成员变量进行值的复制,对引用类型的成员变量也进行<br>引用对象的复制.<br>    （Object 类的 clone 方法只会拷贝对象中的基本数据类型的值，对于数组、<br>容器对象、引用对象等都不会拷贝，这就是浅拷贝。如果要实现深拷贝，必须<br>将原型模式中的数组、容器对象、引用对象等另行拷贝。）</p>
<ul>
<li>原型模式的优点</li>
</ul>
<p>1.如果创建新的对象比较复杂时，可以利用原型模式简化对象的创建过程。<br>2.使用原型模式创建对象比直接 new 一个对象在性能上要好的多，因为<br>Object 类的 clone 方法是一个本地方法，它直接操作内存中的二进制流，特别<br>是复制大对象时，性能的差别非常明显。</p>
<ul>
<li>原型模式的使用场景。</li>
</ul>
<blockquote>
<p>因为以上优点，所以在<strong>需要重复地创建相似对象时可以考虑使用原型模式。</strong>比如需要在一个循环体内创建对象，假如对象创建过程比较复杂或者循环次数很多的话，使用原型模式不但可以简化创建过程，而且可以使系统的整体性能提高很多。</p>
</blockquote>
<ul>
<li>迭代器及迭代器模式</li>
</ul>
<h3 id="工厂、适配器、责任链、观察者"><a href="#工厂、适配器、责任链、观察者" class="headerlink" title="工厂、适配器、责任链、观察者"></a>工厂、适配器、责任链、观察者</h3><p>手写一个工厂模式。<br>外观模式。<br>命令模式<br>组合模式</p>
<blockquote>
<p>常见设计模式，如 singlen，factory，abstract factory，strategy，chain，adaptor，decorator，composite，template，absever 等。</p>
</blockquote>
<ul>
<li>工厂方法模式的优点（低耦合、高内聚，开放封闭原则）</li>
</ul>
<blockquote>
<p>1.观察者设计模式</p>
</blockquote>
<p>观察者模式定义了对象间的一对多依赖关系，让一个或多个观察者对象观察一个<br>主题对象。当主题对象的状态发生变化时，系统能通知所有的依赖于此对象的观察者<br>对象，从而使得观察者对象能够自动更新。<br>在观察者模式中，被观察的对象常常也被称为目标或主题（Subject），依赖的<br>对象被称为观察者（Observer）。</p>
<blockquote>
<p>2.装饰者设计模式</p>
</blockquote>
<p>现在需要一个汉堡，主体是鸡腿堡，可以选择添加生菜、酱、辣椒等等许多其他的<br>配料，这种情况下就可以使用装饰者模式。</p>
<blockquote>
<p>3.工厂设计模式</p>
</blockquote>
<ul>
<li><p>4.1 简单工厂模式</p>
<p>简单工厂模式的实质是由一个工厂类根据传入的参数，动态决定应该创建出哪一个产品类的实例。</p>
</li>
<li><p>4.2 抽象工厂模式</p>
</li>
</ul>
<p>在这个模式中的几类角色,有抽象工厂，实体工厂，抽象产品，实体产品。</p>
<blockquote>
<p><a href="http://www.cnblogs.com/suizhouqiwei/archive/2012/06/26/2563332.html" target="_blank" rel="noopener">http://www.cnblogs.com/suizhouqiwei/archive/2012/06/26/2563332.html</a></p>
</blockquote>
<ul>
<li>4.3 工厂方法模式</li>
</ul>
<blockquote>
<p>内容转载自：内推军_JAVA基础</p>
</blockquote>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/11/01/JAVA-中的集合类/" rel="next" title="JAVA 中的集合类">
                <i class="fa fa-chevron-left"></i> JAVA 中的集合类
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/04/14/Spring-Boot-第一章/" rel="prev" title="Spring Boot - 第一章">
                Spring Boot - 第一章 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.gif" alt="四 季">
            
              <p class="site-author-name" itemprop="name">四 季</p>
              <p class="site-description motion-element" itemprop="description">我的学习笔记站</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-编写线程安全的单例模式。"><span class="nav-number">1.</span> <span class="nav-text">1.编写线程安全的单例模式。</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#实现方式一："><span class="nav-number">1.1.</span> <span class="nav-text">实现方式一：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实现方式二："><span class="nav-number">1.2.</span> <span class="nav-text">实现方式二：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实现方式三："><span class="nav-number">1.3.</span> <span class="nav-text">实现方式三：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#工厂、适配器、责任链、观察者"><span class="nav-number">1.3.1.</span> <span class="nav-text">工厂、适配器、责任链、观察者</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">四 季</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
